/*
 * Copyright (c) 2015-2018 Sfkj Science And Technology Co.,Ltd.
 * All Rights Reserved.
 * This software is the confidential and proprietary information of
 * Sfkj Science And Technology Co.,Ltd.
 * ("Confidential Information").You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Sfkj.
 */
package com.sfkj.walk.query.user;

import com.alibaba.fastjson.JSON;
import com.sfkj.walk.api.user.PhoneUserRegisteredEvent;
import com.sfkj.walk.api.user.UserPasswordChangedEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.axonframework.eventhandling.EventHandler;
import org.axonframework.eventhandling.Timestamp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Objects;

@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Component
class UserListener {

    private final UserRepository repository;

    @EventHandler
    public void on(final PhoneUserRegisteredEvent event, @Timestamp Instant timestamp) {
        log.info("Caught: {}, identifier:{}", event.getClass().getSimpleName(), JSON.toJSONString(event));

        User queryObject = repository.findOne(event.getId());
        if (Objects.isNull(queryObject)) {
            queryObject = new User();
            queryObject.setId(event.getId());
            queryObject.setCreatedDate(LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault()));
        }
        queryObject.setName(event.getName());
        queryObject.setIntroduction(event.getIntroduction());
        queryObject.setPhone(event.getPhone());

        queryObject.setLastUpdate(LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault()));

        repository.save(queryObject);
    }

    @EventHandler
    public void on(final UserPasswordChangedEvent event, @Timestamp Instant timestamp) {
        log.info("Caught: {}, identifier:{}", event.getClass().getSimpleName(), JSON.toJSONString(event));

        User queryObject = repository.findOne(event.getId());
        if (Objects.isNull(queryObject)) {
            queryObject = new User();
            queryObject.setId(event.getId());
            queryObject.setCreatedDate(LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault()));
        }
        queryObject.setPassword(event.getPassword());

        queryObject.setLastUpdate(LocalDateTime.ofInstant(timestamp, ZoneId.systemDefault()));

        repository.save(queryObject);
    }

}
